package com.example.music

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.ImageButton
import android.widget.SeekBar
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.example.music.adapter.MainPagerAdapter
import com.example.music.fragment.MusicPlayFragment
import com.example.music.model.Song
import com.example.music.service.MusicService
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import androidx.lifecycle.lifecycleScope
import com.example.music.network.MusicApi

private const val TAG = "MainActivity"

class MainActivity : AppCompatActivity(), MusicService.OnPlaybackStateChangeListener {
    private lateinit var viewPager: ViewPager2
    private lateinit var tabLayout: TabLayout
    
    lateinit var musicService: MusicService
    private var currentSong: Song? = null
    private var songs: List<Song> = emptyList()
    private var currentSongIndex: Int = 0
    private var pendingPlaySong: Song? = null
    private lateinit var miniSeekBar: SeekBar
    private val handler = Handler(Looper.getMainLooper())
    private val updateProgressRunnable = object : Runnable {
        override fun run() {
            if (::musicService.isInitialized && musicService.isPlaying()) {
                updateProgress()
            }
            handler.postDelayed(this, 1000)
        }
    }

    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val binder = service as MusicService.MusicBinder
            musicService = binder.getService()
            musicService.setPlaybackStateChangeListener(this@MainActivity)
            

            musicService.getPlaybackState().let { (song, position, isPlaying) ->
                currentSong = song
                updatePlayerControlUI()
            }
            
            pendingPlaySong?.let { song ->
                playSong(song)
                pendingPlaySong = null
            }
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            musicService.setPlaybackStateChangeListener(null)
        }
    }

    private lateinit var playerControl: View

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        (application as MyApplication).setMainActivityReference(this)
        setContentView(R.layout.activity_main)
        
        setupViewPager()
        setupPlayerControl()
        bindMusicService()
        startProgressUpdate()
        loadDefaultSongs()
    }

    private fun setupPlayerControl() {
        playerControl = findViewById(R.id.playerControl)
        playerControl.apply {
            miniSeekBar = findViewById(R.id.miniSeekBar)
            miniSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
                override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                    if (fromUser) {
                        musicService.seekTo(progress)
                        progressUpdateListener?.onProgressUpdated(progress, seekBar?.max ?: 0)
                    }
                }
                override fun onStartTrackingTouch(seekBar: SeekBar?) {}
                override fun onStopTrackingTouch(seekBar: SeekBar?) {
                    startProgressUpdate()
                }
            })

            setOnClickListener {
                if (currentSong != null) {
                    startMusicDetail(currentSongIndex, songs)
                }
            }

            findViewById<ImageButton>(R.id.miniListButton).setOnClickListener {
                viewPager.setCurrentItem(2, true)
            }

            findViewById<ImageButton>(R.id.miniPlayPauseButton).setOnClickListener {
                currentSong?.let { song ->
                    if (!musicService.isPlaying()) {
                        if (song.id != musicService.getCurrentSong()?.id) {
                            playSong(song)
                        } else {
                            musicService.start()
                        }
                    } else {
                        if (song.id != musicService.getCurrentSong()?.id) {
                            playSong(song)
                        } else {
                            musicService.pause()
                        }
                    }
                    updatePlayPauseButton(musicService.isPlaying())
                }
            }

            findViewById<ImageButton>(R.id.miniNextButton).setOnClickListener {
                playNext()
            }
        }
    }

    private fun bindMusicService() {
        Intent(this, MusicService::class.java).also { intent ->
            bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
            startService(intent)
        }
    }

    private fun updatePlayerControlUI() {
        currentSong?.let { song ->
            try {
                findViewById<TextView>(R.id.miniTitle).text = song.name
                findViewById<TextView>(R.id.miniArtist).text = song.artist
                
                Glide.with(this)
                    .load(song.coverUrl)
                    .error(R.drawable.default_music_cover)
                    .into(findViewById(R.id.miniCover))
            } catch (e: Exception) {
                Log.e(TAG, "更新UI失败", e)
            }
        }
    }

    fun playPrevious() {
        if (currentSongIndex > 0) {
            currentSongIndex--
            playSong(songs[currentSongIndex])
        }
    }

    fun playNext() {
        if (currentSongIndex < songs.size - 1) {
            currentSongIndex++
            playSong(songs[currentSongIndex])
        }
    }
    fun playSong(song: Song) {
        if (::musicService.isInitialized) {
            if (musicService.isPlaying() && musicService.getCurrentSong()?.id != song.id) {
                musicService.stop()
            }
            
            currentSong = song
            musicService.playSong(song) {
                updatePlaybackState()
            }
        } else {
            pendingPlaySong = song
        }
    }

    private fun updateProgress() {
        if (::musicService.isInitialized) {
            try {
                val duration = musicService.getDuration()
                val position = musicService.getCurrentPosition()
                if (duration > 0) {
                    miniSeekBar.max = duration
                    miniSeekBar.progress = position
                    progressUpdateListener?.onProgressUpdated(position, duration)
                }
            } catch (e: Exception) {
                Log.e(TAG, "更新进度失败", e)
            }
        }
    }

    fun startProgressUpdate() {
        stopProgressUpdate()
        handler.post(updateProgressRunnable)
    }

    fun stopProgressUpdate() {
        handler.removeCallbacks(updateProgressRunnable)
    }

    override fun onResume() {
        super.onResume()
        setPlayerControlVisibility(viewPager.currentItem != 1)
        if (::musicService.isInitialized) {
            updatePlaybackState()
        }
    }

    override fun onPause() {
        super.onPause()
        stopProgressUpdate()
    }

    override fun onDestroy() {
        progressUpdateListener = null
        musicService.setPlaybackStateChangeListener(null)
        stopProgressUpdate()
        unbindService(serviceConnection)
        super.onDestroy()
    }

    private fun setupViewPager() {
        tabLayout = findViewById(R.id.tabLayout)
        viewPager = findViewById(R.id.viewPager)
        
        viewPager.adapter = MainPagerAdapter(this)

        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                setPlayerControlVisibility(position != 1)
            }
        })

        TabLayoutMediator(tabLayout, viewPager) { tab, position ->
            tab.text = when (position) {
                0 -> "音乐推荐"
                1 -> "音乐播放"
                2 -> "音乐列表"
                else -> null
            }
        }.attach()
    }

    private fun startMusicDetail(position: Int, songs: List<Song>) {
        startActivity(Intent(this, MusicDetailActivity::class.java).apply {
            putExtra("song_index", position)
            putExtra("songs", ArrayList(songs))
            addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
        })
    }

    fun getCurrentPlaybackState(): Triple<Song?, Int, Boolean> {
        return Triple(
            currentSong,
            musicService.getCurrentPosition(),
            musicService.isPlaying()
        )
    }

    override fun onPlaybackStateChanged(song: Song?, isPlaying: Boolean) {
        runOnUiThread {
            try {
                currentSong = song
                // 更新所有UI状态
                updatePlaybackState()
                // 通知Fragment状态变化
                (viewPager.adapter as? MainPagerAdapter)?.getCurrentFragment()?.let { fragment ->
                    if (fragment is MusicPlayFragment) {
                        fragment.onPlaybackStateChanged(song, isPlaying)
                    }
                }
            } catch (e: Exception) {
                Log.e(TAG, "更新播放状态失败", e)
            }
        }
    }

    fun updateCurrentSong(song: Song, index: Int, songList: List<Song>) {
        val isNewSong = currentSong?.id != song.id
        
        currentSong = song
        currentSongIndex = index
        songs = songList
        updatePlayerControlUI()
        
        if (isNewSong) {
            playSong(song)
        }
    }

    private fun loadDefaultSongs() {
        val musicApi = createMusicApi()
        
        lifecycleScope.launch {
            try {
                val playlists = musicApi.getPlaylists()
                if (playlists.isNotEmpty()) {
                    val songs = playlists.map { pl ->
                        Song(
                            id = pl.id,
                            name = pl.name,
                            artist = pl.artist?.takeIf { it.isNotBlank() },
                            coverUrl = pl.coverUrl,
                            url = pl.url
                        )
                    }
                    currentSong = songs[0]
                    currentSongIndex = 0
                    this@MainActivity.songs = songs
                    updatePlayerControlUI()
                }
            } catch (e: Exception) {
                Log.e(TAG, "加载默认歌曲失败", e)
            }
        }
    }

    private fun createMusicApi(): MusicApi {
        val client = OkHttpClient.Builder()
            .addInterceptor(HttpLoggingInterceptor().apply { 
                level = HttpLoggingInterceptor.Level.BASIC 
            })
            .connectTimeout(15, TimeUnit.SECONDS)
            .build()

        return Retrofit.Builder()
            .baseUrl("http://121.37.40.55:3000/")
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(MusicApi::class.java)
    }

    interface OnProgressUpdateListener {
        fun onProgressUpdated(position: Int, duration: Int)
    }

    private var progressUpdateListener: OnProgressUpdateListener? = null

    fun setProgressUpdateListener(listener: OnProgressUpdateListener?) {
        progressUpdateListener = listener
    }

    private fun updatePlayPauseButton(isPlaying: Boolean) {
        findViewById<ImageButton>(R.id.miniPlayPauseButton).setImageResource(
            if (isPlaying) R.drawable.ic_pause else R.drawable.ic_play
        )
    }

    fun updatePlaybackState() {
        if (::musicService.isInitialized) {
            try {
                val duration = musicService.getDuration()
                val position = musicService.getCurrentPosition()
                if (duration > 0) {
                    miniSeekBar.max = duration
                    miniSeekBar.progress = position
                    progressUpdateListener?.onProgressUpdated(position, duration)
                }
                updatePlayPauseButton(musicService.isPlaying())
                updatePlayerControlUI()
                startProgressUpdate()
            } catch (e: Exception) {
                Log.e(TAG, "更新播放状态失败", e)
            }
        }
    }

    fun setPlayerControlVisibility(visible: Boolean) {
        playerControl.visibility = if (visible) View.VISIBLE else View.GONE
    }
}